<template>
    <div class="nav">
        <el-form>
            <el-form-item label="创建时间" style="width: 308px">
                <el-date-picker v-model="dateRange" value-format="YYYY-MM-DD" type="daterange" range-separator="-"
                    start-placeholder="开始日期" end-placeholder="结束日期" @change="handleDateChange"></el-date-picker>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="fetchTableData">搜索</el-button>
                <el-button @click="resetFilters">重置</el-button>
            </el-form-item>
        </el-form>
        <div class="content">
            <v-chart class="chart" :option="pieOption" />
            <v-chart class="line-chart" :option="lineOption" />
        </div>

        <el-table :data="tableData" style="width: 100%" :row-class-name="tableRowClassName">
            <el-table-column prop="name" label="活动名称" width="180" />
            <el-table-column prop="count" label="线索数量" width="180" />
            <el-table-column prop="available" label="线索有效率" />
        </el-table>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue'
import VChart from 'vue-echarts';
import * as echarts from 'echarts/core';
import { PieChart, LineChart } from 'echarts/charts';
import { TitleComponent, TooltipComponent, LegendComponent, GridComponent } from 'echarts/components';
import { CanvasRenderer } from 'echarts/renderers';

import { listRole } from '@/api/system/anuser'

// 注册必须的组件
echarts.use([PieChart, LineChart, TitleComponent, TooltipComponent, LegendComponent, GridComponent, CanvasRenderer])

interface User {
    name: string
    count: number
    available: string
}

const tableRowClassName = ({ row, rowIndex }: { row: User; rowIndex: number }) => {
    if (rowIndex === 1) {
        return 'warning-row'
    } else if (rowIndex === 3) {
        return 'success-row'
    }
    return ''
}

const tableData = ref<User[]>([])
const pieOption = reactive({
    title: {
        text: '活动总数分析',
        left: 'center'
    },
    tooltip: {
        trigger: 'item'
    },
    legend: {
        orient: 'vertical',
        left: 'left'
    },
    series: [
        {
            name: '线索有效率',
            type: 'pie',
            radius: '75%',
            data: [],
            emphasis: {
                itemStyle: {
                    shadowBlur: 10,
                    shadowOffsetX: 0,
                    shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
            }
        }
    ]
})

const lineOption = reactive({
    title: {
        text: '折线图示例',
        left: 'center'
    },
    tooltip: {
        trigger: 'axis'
    },
    xAxis: {
        type: 'category',
        data: []
    },
    yAxis: {
        type: 'value',
        min: 0,          // 设置 Y 轴的最小值
        max: 1,        // 设置 Y 轴的最大值
        interval: 0.2     // 设置 Y 轴刻度的间隔
    },
    series: [
        {
            name: '访问量',
            type: 'line',
            data: []
        }
    ]
})

const dateRange = ref<string[]>([])
const searchQuery = ref<string>('')

const handleDateChange = (value: string[]) => {
    console.log('Date range changed:', value)
}

const handleSearch = (value: string) => {
    console.log('Search query changed:', value)
}

const fetchTableData = async () => {
    try {
        const params = {
            pageNum: 1,
            pageSize: 10,
            'dateRange[0]': dateRange.value[0] ? `${dateRange.value[0]} 12:00:00` : '',
            'dateRange[1]': dateRange.value[1] ? `${dateRange.value[1]} 12:00:00` : '',
            'params[beginTime]': dateRange.value[0] ? `${dateRange.value[0]} 12:00:00` : '',
            'params[endTime]': dateRange.value[1] ? `${dateRange.value[1]} 12:00:00` : '',
            search: searchQuery.value
        }

        // 过滤掉空值
        const filteredParams = Object.fromEntries(Object.entries(params).filter(([_, value]) => value !== ''))

        const response = await listRole(filteredParams)
        tableData.value = response.data
        console.log(response.data);

        // 更新饼图数据
        pieOption.series[0].data = response.data.map(item => ({
            value: item.count,
            name: item.name
        }))
        console.log(pieOption.series[0].data);

        // 更新折线图数据
        lineOption.xAxis.data = response.data.map(item => item.name);
        lineOption.series[0].data = response.data.map(item => parseFloat(item.available));

        console.log(lineOption.xAxis.data);
        console.log(lineOption.series[0].data);
    } catch (error) {
        console.error('Error fetching data:', error)
    }
}

const resetFilters = () => {
    dateRange.value = []
    searchQuery.value = ''
    fetchTableData()
}

onMounted(() => {
    fetchTableData()
})
</script>

<style scoped>
.nav {
    width: 100%;
    height: 100%;
}

.content {
    width: 900px;
    height: 800px;
    /* 增加高度以容纳两个图表 */
    /* background-color: red */
}

.el-form {
    display: flex;
    justify-content: start;
}

::v-deep .el-form-item__content {
    margin-left: 20px;
}

.chart {
    width: 1200px;
    height: 400px;
}

.line-chart {
    width: 1200px;
    height: 400px;
}

.canvas {
    width: 1200px;
    height: 400px;
    background-color: aqua;
}

.el-table .warning-row {
    --el-table-tr-bg-color: var(--el-color-warning-light-9);
}

.el-table .success-row {
    --el-table-tr-bg-color: var(--el-color-success-light-9);
}
</style>